/**
 *
 */
package org.yabam.action;

import static net.sourceforge.stripes.validation.ValidationState.NO_ERRORS;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.util.StringUtil;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.yabam.model.Owner;

/**
 * @author brisssou
 *
 */
public class LoginAction extends YabamActionBean {

	@ValidateNestedProperties({
		@Validate(field="login", required = true),
		@Validate(field="password", required = true)
	})
	private Owner owner;

	private String targetUrl;

	@ValidationMethod(priority=0)
	public void userExists(ValidationErrors errors) {
		String login = this.owner.getLogin();
		Owner owner = Owner.get(login);
		if (owner==null) {
			errors.add("owner.login", new LocalizableError("login.username.doesnotexists", login));
		}
	}

	@ValidationMethod(priority=100, when=NO_ERRORS)
	public void passwordIsOk(ValidationErrors errors) {
		Owner owner = Owner.get(this.owner.getLogin());
		if (!owner.getPassword().equals(this.owner.getPassword())) {
			errors.add("owner.password", new LocalizableError("login.passwd.incorrect"));
		}
	}

	public Resolution login() {
		getContext().setLoggedOwner(Owner.get(owner.getLogin()));
		if (!org.yabam.util.StringUtil.empty(targetUrl) && !"/Login.action".equals(targetUrl)) {
			return new ForwardResolution(StringUtil.urlDecode(targetUrl));
		}
		return new ForwardResolution("/Home.action");
	}

	/**
	 * @return the targetUrl
	 */
	public String getTargetUrl() {
		return targetUrl;
	}

	/**
	 * @param targetUrl
	 *            the targetUrl to set
	 */
	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}

	/**
	 * @return the owner
	 */
	public Owner getOwner() {
		return owner;
	}

	/**
	 * @param owner the owner to set
	 */
	public void setOwner(Owner owner) {
		this.owner = owner;
	}


}
